package com.sky.task;

import com.alibaba.druid.sql.dialect.mysql.visitor.transform.OrderByResolve;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */

    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeOutOrder(){
        LocalDateTime now = LocalDateTime.now();
        log.info("处理超时订单：{}", now);
        LocalDateTime localDateTime = LocalDateTime.now().plusSeconds(-15);
        List<Orders> ordersList = orderMapper.processByStatusAndTimeOutLT(Orders.PENDING_PAYMENT,localDateTime);
        if (ordersList != null && ordersList.size() > 0) {//判断是否为空
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(now);
                orders.setCancelReason("订单超时");
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 每天凌晨一点统一处理派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveryOrders(){
        log.info("每天凌晨一点统一处理派送中订单，{}",LocalDateTime.now());
        LocalDateTime localDateTime = LocalDateTime.now().plusSeconds(-60);
        List<Orders> ordersList = orderMapper.processByStatusAndTimeOutLT(Orders.DELIVERY_IN_PROGRESS,localDateTime);
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(localDateTime);
                orderMapper.update(orders);
            }
        }
    }

}
